package work.mediway.common.util;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 格式化json<br/>
 * java去掉String里面的空格、回车、换行符、制表符等
 *
 * @author zhongyj <1126834403@qq.com><br/>
 * @date 2023/8/29
 */
@Slf4j
public class JsonUtil {

    public static final String EMPTY = "";
    /**
     * 替换所有空格，留下一个
     */
    private static final String REPLACE_BLANK_ENTER = "\\s{2,}|\t|\r|\n";
    private static final Pattern REPLACE_P = Pattern.compile(REPLACE_BLANK_ENTER);

    /**
     * 使用正则表达式删除字符串中的空格、回车、换行符、制表符
     *
     * @param str String
     * @return String
     */
    public static String replaceAllBlank(String str) {
        String dest = "";
        if (StringUtils.isNotBlank(str)) {
            Matcher m = REPLACE_P.matcher(str);
            dest = m.replaceAll("");
        }
        return dest;
    }

    /**
     * 去除字符串中的空格、回车、换行符、制表符
     * \n 回车(\u000a)
     * \t 水平制表符(\u0009)
     * \s 空格(\u0008)
     * \r 换行(\u000d)
     *
     * @param source
     * @return
     */
    public static String replaceBlank(String source) {
        String ret = EMPTY;
        if (StringUtils.isNotBlank(source)) {
            ret = source.replaceAll(StringUtils.LF, EMPTY)
                    .replaceAll("\\s{2,}", EMPTY)
                    .replaceAll("\\t", EMPTY)
                    .replaceAll(StringUtils.CR, EMPTY);
        }
        return ret;
    }

    /**
     * 使用fastjson JSONObject格式化输出JSON字符串
     *
     * @param source String
     * @return String
     */
    public static String formatJson(String source) {
        JSONObject object = JSONObject.parseObject(source);
        return JSON.toJSONString(object, SerializerFeature.PrettyFormat,
                SerializerFeature.WriteMapNullValue,
                SerializerFeature.WriteDateUseDateFormat);
    }

    public static String formatJsonOneRow(String source) {
        JSONObject object;
        try {
            object = JSONObject.parseObject(source);
        } catch (Exception e) {
            log.error("JSON格式化异常, 数据【{}】", source);
            try {
                object = JSONObject.parseObject(StrUtil.removeSuffix(source, "}"));
            } catch (Exception exception) {
                return source;
            }
        }
        return JSON.toJSONString(object, SerializerFeature.PrettyFormat,
                SerializerFeature.WriteMapNullValue,
                SerializerFeature.WriteDateUseDateFormat);
    }
}
